'use strict';

var clientUtils = angular.module('clientUtils');

clientUtils.factory('DomUtil', ['$http', 'Constant', function($http, Constant){
    return {
        loadComponent : function(component, callback){
            var fileType = component.substring(component.lastIndexOf('.'));
            var head = document.getElementsByTagName("head")[0];
            var done = false;

            var id = component.replace(new RegExp('/',"g"), '_')
                .replace(new RegExp('\\.',"g"), '_');
            var elm = document.getElementById(id);
            if (fileType === ".js" || component.indexOf("jsapi") > -1) {
                if (elm == null) {
                    var fileRef = document.createElement('script');
                    fileRef.setAttribute("id", id);
                    fileRef.setAttribute("type", "text/javascript");
                    var path = component;
                    if (component.indexOf("jsapi") == -1) {
                        path += '?version=';
                    }
                    fileRef.setAttribute("src", path);
                    fileRef.onload = fileRef.onreadystatechange = function(){
                        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) {
                            done = true;
                            if (callback) {
                                callback();
                            }
                        }
                    };
                    if (typeof fileRef != "undefined") {
                        head.appendChild(fileRef);
                    }
                } else {
                    callback();
                }
            }
            else if (fileType === ".css") {
                if (elm == null) {
                    var fileRef = document.createElement("link");
                    fileRef.setAttribute("id", id);
                    fileRef.setAttribute("type", "text/css");
                    fileRef.setAttribute("rel", "stylesheet");
                    var path = component + '?version=' + new Date().getTime();
                    fileRef.setAttribute("href", path);
                    if (typeof fileRef != "undefined") {
                        head.appendChild(fileRef);
                    }
                }
            }
        },
        getColumnWidth: function(viewWidth, gutter){

            var colNumb;
            if (viewWidth <= 480) {
                colNumb = 2;
            } else if (viewWidth > 480 && viewWidth <= 800) {
                colNumb = 3;
            } else if (viewWidth > 800 && viewWidth <= 1200) {
                colNumb = 4;
            } else {
                colNumb = 5;
            }

            var columnWidth = Math.floor(viewWidth / colNumb);
            var contentWidth = columnWidth - gutter;

            return contentWidth;
        }
    }
}]);